package com.enation.app.javashop.consumer.shop.pagecreate.service.impl;

import com.enation.app.javashop.consumer.shop.pagecreate.service.PageCreator;
import com.enation.app.javashop.core.base.SettingGroup;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.client.system.SettingClient;
import com.enation.app.javashop.core.client.system.StaticsPageHelpClient;
import com.enation.app.javashop.core.pagecreate.model.PageCreatePrefixEnum;
import com.enation.app.javashop.core.system.enums.ClientType;
import com.enation.app.javashop.core.system.model.vo.PageSetting;
import com.enation.app.javashop.core.system.progress.model.TaskProgress;
import com.enation.app.javashop.core.system.progress.model.TaskProgressConstant;
import com.enation.app.javashop.core.system.progress.service.ProgressManager;
import com.enation.app.javashop.framework.util.JsonUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 静态页向redis生成
 *
 * @author zh
 * @version v1.0
 * @since v6.4.0 2017年8月29日 上午11:45:20
 */
@Component
public class RedisPageCreator implements PageCreator {

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProgressManager progressManager;

    @Autowired
    private SettingClient settingClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private StaticsPageHelpClient staticsPageHelpClient;

    @Override
    public void createOne(String path, String type, String name) throws Exception {
        //生成消息
        String url = getUrl(path, type);
        //通过http 来获取html存储redis
        String html = this.getHTML(url, type);
        stringRedisTemplate.opsForValue().set(name, html);

    }

    @Override
    public void createAll() throws Exception {
        //生成商品信息页面
        this.createGoods();
        //生成商城首页
        this.createIndex();
        //生成帮助中心页面
        this.createHelp();
    }

    @Override
    public void createIndex() throws Exception {
        //生成静态页
        this.createOne("/", ClientType.PC.name(), "/" + ClientType.PC.name() + "/");
        this.createOne("/", ClientType.WAP.name(), "/" + ClientType.WAP.name() + "/");
        this.showMessage("/");
        this.createOne("/index.html", ClientType.PC.name(), "/" + ClientType.PC.name() + "/index.html");
        this.createOne("/index.html", ClientType.WAP.name(), "/" + ClientType.WAP.name() + "/index.html");
        this.showMessage("/index.html");
    }

    @Override
    public void createGoods() throws Exception {
        //为了防止首页有相关商品，所以需要生成首页一次
        this.createIndex();
        //商品总数
        int goodsCount = goodsClient.queryGoodsCount();
        //100条查一次
        int pageSize = 100;
        int pageCount = 0;
        pageCount = goodsCount / pageSize;
        pageCount = goodsCount % pageSize > 0 ? pageCount + 1 : pageCount;
        for (int i = 1; i <= pageCount; i++) {
            //100条查一次
            List<Map> goodsList = this.goodsClient.queryGoodsByRange(i, pageSize);
            for (Map goods : goodsList) {
                int goodsId = Integer.valueOf(goods.get("goods_id").toString());
                //商品页面名称
                String pageName = PageCreatePrefixEnum.GOODS.getHandlerGoods(goodsId);
                //生成静态页
                this.createOne(pageName, ClientType.PC.name(), "/" + ClientType.PC.name() + pageName);
                this.createOne(pageName, ClientType.WAP.name(), "/" + ClientType.WAP.name() + pageName);
                this.showMessage(pageName);
            }
        }
    }


    @Override
    public void createHelp() throws Exception {
        //帮助中心页面
        int helpCount = staticsPageHelpClient.count();
        // 100条查一次
        int pageSize = 100;
        int pageCount = 0;
        pageCount = helpCount / pageSize;
        pageCount = helpCount % pageSize > 0 ? pageCount + 1 : pageCount;
        for (int i = 1; i <= pageCount; i++) {
            //获取数据
            List<Map> list = this.staticsPageHelpClient.helpList(i, pageSize);
            for (Map map : list) {
                int articleId = StringUtil.toInt(map.get("id"), false);
                String pageName = (PageCreatePrefixEnum.HELP.getHandlerHelp(articleId));
                //生成静态页
                String name = "/" + ClientType.PC.name() + pageName;
                this.createOne(pageName, ClientType.PC.name(), name);
                this.showMessage(pageName);
            }
        }
    }

    @Override
    public void deleteGoods(String name) throws Exception {

        this.stringRedisTemplate.delete(name);

    }

    /**
     * 传入url 返回对应页面的html
     *
     * @param url  页面的url
     * @param type 客户端类型
     * @return 返回对应页面的html
     * @throws ClientProtocolException
     * @throws IOException
     */
    private String getHTML(String url, String type) throws ClientProtocolException, IOException {
        String html = "null";
        // socket超时  connect超时
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000)
                .setConnectTimeout(50000)
                .build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Client-Type", type);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        html = EntityUtils.toString(response.getEntity(), "utf-8");
        return html;
    }

    /**
     * 获取url
     *
     * @param path 路径
     * @param type 客户端类型
     * @return url
     */
    private String getUrl(String path, String type) {
        String pageSettingJson = settingClient.get(SettingGroup.PAGE);
        PageSetting pageSetting = JsonUtil.jsonToObject(pageSettingJson, PageSetting.class);

        String url = pageSetting.getStaticPageAddress() + "/" + path;
        if (type.equals(ClientType.WAP.name())) {
            url = pageSetting.getStaticPageWapAddress() + "/" + path;
        }
        return url;
    }

    /**
     * 生成消息
     *
     * @param path 路径
     */
    private void showMessage(String path) {
        try {
            TaskProgress tk = progressManager.getProgress(TaskProgressConstant.PAGE_CREATE);
            if (tk == null) {
                return;
            }
            tk.step("正在生成[" + path + "]");
            progressManager.putProgress(TaskProgressConstant.PAGE_CREATE, tk);
        } catch (Exception e) {
            logger.error(e);
        }
    }
}
